import React from 'react';
import PropTypes from 'prop-types';
import { Upload, Modal, Icon } from 'antd';
import _ from 'lodash';
import { getToken } from '@/utils/auth';

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default class ImageUpload extends React.Component {
  static defaultProps = {
    num: 1,
    onChange: () => {},
  };

  static propTypes = {
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
    num: PropTypes.number,
    onChange: PropTypes.func,
  };

  constructor(props) {
    super(props);
    const { num, value } = props;
    const fileList = [];
    if (value && value.length) {
      if (num === 1) {
        fileList.push({ uid: '-1', name: value, status: 'done', url: value })
      } else {
        value.forEach((image, index) => {
          fileList.push({ uid: -(index + 1), name: image, status: 'done', url: image })
        })
      }
    }
    this.state = { previewVisible: false, previewImage: '', fileList };
  }

  beforeUpload = file => {
    const isJPG = file.type === 'image/jpeg';
    const isJPEG = file.type === 'image/jpeg';
    const isGIF = file.type === 'image/gif';
    const isPNG = file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!(isJPG || isJPEG || isGIF || isPNG)) {
      Modal.error({
        title: '只能上传JPG 、JPEG 、GIF、 PNG格式的图片~',
      });
    } else if (!isLt2M) {
      Modal.error({
        title: '超过2M限制，不允许上传~',
      });
    }
    return new Promise((resolve, reject) => {
      if (!(isJPG || isJPEG || isGIF || isPNG)) {
        reject(file);
      } else {
        resolve(file);
      }
    });
  };

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    });
  };

  handleChange = ({ fileList }) => {
    const { onChange, num } = this.props;
    const filePathList = [];
    _.filter(fileList, item => {
      if (item.status === 'done') {
        filePathList.push(item.url || item.response.data);
      }
      return item.status === 'error' || item.status === 'removed';
    });
    this.setState({ fileList });
    if (num === 1) {
      onChange(filePathList[0] || '')
    } else {
      onChange(filePathList);
    }
  };

  render() {
    const { num } = this.props;
    const { previewVisible, previewImage, fileList } = this.state;

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );

    const uploadProps = {
      fileList,
      accept: 'image/*',
      action: `${UPLOAD_FILE_PATH}`,
      headers: { Authorization: `Bearer ${getToken() || ''}` },
      beforeUpload: this.beforeUpload,
      listType: 'picture-card',
      onPreview: this.handlePreview,
      onChange: this.handleChange,
    };

    return (
      <div className="clearfix">
        <Upload {...uploadProps}>
          {fileList.length >= num ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}
